import Cookies from 'js-cookie'
import config from '../config'

const { global, cookie } = config

// Token相关
export const getToken = () => Cookies.get(global.project + '-token')

export const setToken = (token) => Cookies.set(global.project + '-token', token, { expires: cookie.expires || 1 })

export const removeToken = () => Cookies.remove(global.project + '-token')

// LocalStorage相关
export const getLocalStorage = (key) => localStorage.getItem(global.project + '-' + key)

export const setLocalStorage = (key, value) => localStorage.setItem(global.project + '-' + key, value)

export const removeLocalStorage = (key) => localStorage.removeItem(global.project + '-' + key)

// 清除所有缓存
export const clearCache = () => {
  removeToken()
  localStorage.clear()
}
const formatTen = (num) => {
  return num > 9 ? (num + "") : ("0" + num);
}

export const formatDate = (date) => {
  date = date ? new Date(date) : new Date()
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  let second = date.getSeconds();
  return year + formatTen(month) + formatTen(day) + formatTen(hour) + formatTen(minute) + formatTen(second);
}

// 判断数据类型
const isString = (value) => Object.prototype.toString.call(value) === '[object String]'

const isNull = (value) => Object.prototype.toString.call(value) === '[object Null]'

const isNumber = (value) => Object.prototype.toString.call(value) === '[object Number]'

const isBoolean = (value) => Object.prototype.toString.call(value) === '[object Boolean]'

const isUndefined = (value) => Object.prototype.toString.call(value) === '[object Undefined]'

const isArray = (value) => Object.prototype.toString.call(value) === '[object Array]'

const isFunction = (value) => Object.prototype.toString.call(value) === '[object Function]'

const isObject = (value) => Object.prototype.toString.call(value) === '[object Object]'

const getHost = () => {
  // 获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
  let curWwwPath = window.document.location.href;
  // 获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
  let pathName = window.document.location.pathname;
  let pos = curWwwPath.indexOf(pathName);
  // 获取主机地址，如： http://localhost:8083
  let localhostPath = curWwwPath.substring(0, pos);
  return localhostPath;
}

export const getUrlParam = (val) => {
  var query = window.location.search ? window.location.search.substring(1) : window.location.href.split('?')[1];
  var vars = query.split("&");
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    if (pair[0] == val) { return decodeURIComponent(pair[1]); }
  }
  return (false);
}

export default {
  isString,
  isNull,
  isNumber,
  isBoolean,
  isUndefined,
  isArray,
  isFunction,
  isObject,
  getHost
}
